import React, { useState } from 'react';
import { cline, GridTable, useCmd, WaitUmd, KFind, useKForm, show_mt, obj_str, PanelTitle,
    save_xlsx, obj_int, obj_str_trim, ck_float, to_float, uDb, Btn, is_empty, loc } from 'sui';

const GtStdView = ({ title, mod, col, high, map_supply, lst_ball, lst_std }) => {
    const [row, setRow] = useState();
    const [sum, setSum] = useState([]);
    const umd = useCmd();
    const form = useKForm();

    const hcalc = () => {
        const ck = {
            ball: v => ck_float(v),
            std: v => ck_float(v),
        };

        if (form.isErr(ck)) {
            return;
        }

        const ball = "" + to_float(form.get("ball"));
        const std = form.get("std");

        umd.startWait();

        uDb(null, `${mod}/list`, { line: cline() },
            r => {
                let dnum = 0;

                const f = r.filter(d => {
                    const t_dnum = obj_int(d, "dnum");
                    const t_ball = obj_str_trim(d, "ball");

                    if (t_dnum <= 0) {
                        return false;
                    }

                    if (t_ball !== ball) {
                        return false;
                    }

                    if (std !== obj_str_trim(d, "std")) {
                        return false;
                    }

                    dnum += t_dnum;

                    return true;
                });

                f.forEach((d, i) => d["index"] = i + 1);

                setRow(f);
                setSum([{ index: loc("l_595"), sn: dnum }])

                umd.endWait();
            },
            e => {
                setRow(null);
                setSum([]);
                umd.setErr();
            });
    };

    const censusCol = () => {
        if (is_empty(col)) {
            return null;
        }

        let val = ["sn", "ball", "dnum", "std", "sub", "level"];

        const set = new Set();

        val.forEach(d => set.add(d));

        return col.filter(d => set.has(d.sn));
    };

    const getCol = () => {
        const col_cen = censusCol();

        if (is_empty(col_cen)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, summaryFormatter: ({ row }) => <strong>{obj_str(row, "index")}</strong>}
        ];

        col_cen.forEach(d => {
            if (d.sn === "supply") {
                tmp.push({name: d.name, key: d.sn, width: 150, formatter: props => {
                    let sn = obj_str(props.row, "supply");

                    const tmp = obj_str(map_supply, sn);
                    if (tmp) {
                        sn = tmp;
                    }

                    return sn;
                }});
            } else if (d.sn === "sn") {
                tmp.push({name: d.name, key: d.sn, width: 150, summaryFormatter: ({ row }) => <strong>{obj_str(row, "sn")}</strong>});
            } else {
                show_mt(tmp, d, 150);
            }
        });

        return tmp;
    };

    const hExport = () => {
        umd.startWait();

        const col_cen = getCol();
        if (is_empty(col_cen) || is_empty(row)) {
            umd.setErr(loc("l_276"));
        }

        const col_c = [];
        const h = [];

        col_cen.forEach(d => {
            h.push({ value: d.name });
            col_c.push(d.key);
        });

        const out = [h];

        row.forEach(d => {
            const tmp = [];
            col_c.forEach(t => tmp.push({ value: obj_str(d, t) }));

            out.push(tmp);
        });

        if (!is_empty(sum)) {
            out.push([{ value: "" }]);

            sum.forEach(d => {
                out.push([
                    { value: d["index"] },
                    { value: d["sn"] },
                ]);
            });
        }

        save_xlsx(out, `${title}_${loc("l_793")}_${loc("l_827")}_${form.get("ball")}.xlsx`, umd);
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn hcmd={hExport} color="green" className="mr-4">{loc("l_519")}</Btn>
        </div>
    );

    const Left = () => (
        <div className="inline-flex">
            <Btn hcmd={() => hcalc()} color="teal" className="mr-4">{loc("l_332")}</Btn>
            <KFind label={loc("l_714")} form={form} name="ball" margin="dense" width="w-56" className="mr-4" list={lst_ball}/>
            <KFind label={loc("l_715")} form={form} name="std" margin="dense" width="w-56" className="mr-4" list={lst_std}/>
        </div>
    );

    return (
        <div>
            <PanelTitle left={<Left/>} right={<Right/>} cl="gray"/>
            <GridTable col={getCol()} row={row} high={high} sumrow={sum}/>
            <WaitUmd umd={umd}/>
        </div>
    );
};

export {GtStdView};
